﻿using MvcSimplyCleverResources;
using MvcSimplyCleverPart3.Models;
using SimplyCleverMiddleTier;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.Mvc;

namespace MvcSimplyCleverPart3
{
    public class SimplyCleverModelMetadataProvider : DataAnnotationsModelMetadataProvider
    {
        readonly CountryData[] metadataCountries = null;

        public SimplyCleverModelMetadataProvider()
        {
            this.metadataCountries = CountryProvider.GetCountries();
        }

        protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
        {
            // invoke the base method but skip the DisplayAttribute since it will use resource internally
            //var attributesWithoutDisplay = attributes.Where(a => a.GetType() != typeof(DisplayAttribute));

            var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);


            if (modelAccessor != null && containerType == typeof(AddressViewModel) && string.IsNullOrEmpty(metadata.DisplayName))
            {
                object target = modelAccessor.Target;
                AddressViewModel address = target.GetType().GetField("container").GetValue(target) as AddressViewModel;
                
                var metadataCountry = metadataCountries.FirstOrDefault(mc => mc.Code.Equals(address.CountryCode));
                

                try
                {
                     var key = "Address" +  metadataCountry.AddressFormatInfo.FieldLabels.First(l => l.Key.Equals(propertyName)).Value;
                    string name = SimplyCleverResources.ResourceManager.GetString(key);
                    
                    metadata.DisplayName = name;
                   
                    bool isRequred = metadataCountry.AddressFormatInfo.FieldRules.First(fr => fr.FieldKey.Equals(propertyName)).Rules.Any(r => r.Key.Equals("Required"));
                    if (isRequred)
                        metadata.DisplayName += "*";
                }
                catch
                {

                }
            }

            return metadata;
        }
    }
}